package com.cameron.ucenter.controller;


import com.cameron.servicebase.config.exception.BusinessException;
import com.cameron.entity.UcenterMember;
import com.cameron.ucenter.service.UcenterMemberService;
import com.cameron.ucenter.utils.HttpClientUtils;
import com.cameron.ucenter.utils.WxConstant;
import com.cameron.utils.JwtUtils;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

@CrossOrigin
@RequestMapping("/service-user/wx")
@Controller
@Slf4j
public class WxApiController {

    @Resource
    private UcenterMemberService memberService;

    @GetMapping("callback")
    public String callback(String code, String state) {
        log.info("code = {}", code);
        log.info("state = {}", state);
        String baseAccessTokenUrl =
                "https://api.weixin.qq.com/sns/oauth2/access_token" +
                        "?appid=%s" +
                        "&secret=%s" +
                        "&code=%s" +
                        "&grant_type=authorization_code";
        String accessTokenUrl = String.format(
                baseAccessTokenUrl,
                WxConstant.WX_OPEN_APP_ID,
                WxConstant.WX_OPEN_APP_SECRET,
                code
        );

        try {
            //调用httpClient 发送get请求获取accessToken
            //返回json格式的字符串
            String res = HttpClientUtils.get(accessTokenUrl);
            log.info(res);
            Gson gson = new Gson();
            HashMap tokenMap = gson.fromJson(res, HashMap.class);
            String openid = (String) tokenMap.get("openid");
            String accessToken = (String) tokenMap.get("access_token");
            //通过Openid获取用户
            UcenterMember member = memberService.getByOpenid(openid);
            //若用户为空则 将用户添加到数据库
            if (member == null) {
                //通过openid和accessToken调用微信官方提供的api获取用户的信息（头像昵称等）
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openid);
                //发送请求
                String userInfo = HttpClientUtils.get(userInfoUrl);
                log.info(userInfo);
                HashMap userInfoMap = gson.fromJson(userInfo, HashMap.class);
                //获取昵称和头像
                String nickname = (String) userInfoMap.get("nickname");
                String headImgUrl = (String) userInfoMap.get("headimgurl");

                member = new UcenterMember();
                member.setOpenid(openid);
                member.setNickname(nickname);
                member.setAvatar(headImgUrl);
                memberService.save(member);
            }
            log.info("user-info:{}", member);
            //使用JWT将member的数据生成token字符串
            String memberToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());
            return "redirect:http://localhost:3000/?token=" + memberToken;

        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            throw new BusinessException(20001, "登录失败！");
        }

    }

    @GetMapping("login")
    public String getQrCode() {
        // 微信开放平台授权baseUrl
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";
        // 回调地址
        String redirectUrl = WxConstant.WX_OPEN_REDIRECT_URL; //获取业务服务器重定向地址
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8"); //url编码
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 防止csrf攻击（跨站请求伪造攻击）
        //String state = UUID.randomUUID().toString().replaceAll("-", "");//一般情况下会使用一个随机数
        String state = "imhelen";//为了让大家能够使用我搭建的外网的微信回调跳转服务器，这里填写你在ngrok的前置域名
        System.out.println("state = " + state);
        // 采用redis等进行缓存state 使用sessionId为key 30分钟后过期，可配置
        //键："wechar-open-state-" + httpServletRequest.getSession().getId()
        //值：satte
        //过期时间：30分钟

        //生成qrcodeUrl
        String qrcodeUrl = String.format(
                baseUrl,
                WxConstant.WX_OPEN_APP_ID,
                redirectUrl,
                state);
        return "redirect:" + qrcodeUrl;
    }
}
